package com.netclass.meethealth.net;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.util.Map;

/**
 * Created by luodong on 15/11/21.
 */
public class XClient {
    // 全局的HttpUtils对象
    private static HttpUtils httpUtils = null;
    //单例
    private static XClient xClient = null;
    //服务器地址
    public final static String baseUrl = "http://2.luodongseu.sinaapp.com/index.php?act=";

    //初始化链接对象
    public void init() {
        if (XClient.httpUtils == null) {
            httpUtils = new HttpUtils();
            httpUtils.configTimeout(30000);     //30秒超时
        }
    }


    //获取单例对象
    public static XClient getInstance(){
        if(xClient == null){
            xClient = new XClient();
        }
        return xClient;

    }

    /**
     * 发送POST请求
     *
     * @param url    地址
     * @param rb     成功回调函数
     * @param params 传递参数
     */
    public void doPost(String url, Map<String, String> params, RequestCallBack rb) {
        RequestParams data = new RequestParams();

        if (params != null)
            for (String key : params.keySet()) {
                data.addBodyParameter(key, params.get(key));
            }

        if (XClient.httpUtils == null) {
            init();
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, url, data, rb);
    }

    /**
     * 发送GET请求
     *
     * @param url
     * @param params
     * @param rb
     */
    public void doGet(String url, Map<String, String> params, RequestCallBack rb) {
        RequestParams data = new RequestParams();

        if (params != null)
            for (String key : params.keySet()) {
                data.addQueryStringParameter(key, params.get(key));//选择addQueryStringParameter还是addBodyParameter是根据服务器那边是否有url param来定的
            }

        if (XClient.httpUtils == null) {
            init();
        }
        httpUtils.send(HttpRequest.HttpMethod.GET, url, data, rb);
    }

    /**
     * 上传文件请求
     *
     * @param url
     * @param params
     * @param rb
     */
    public void uploadFile(String url, Map<String, String> params, RequestCallBack rb) {
        RequestParams data = new RequestParams();

        if (params != null)
            for (String key : params.keySet()) {
                data.addBodyParameter(key, new File(params.get(key)));
            }

        if (XClient.httpUtils == null) {
            init();
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, url, data, rb);
    }


}
